package tt.dz.tcp.socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by luoyp on 2016/7/20.
 * MessageFuture的默认实现
 */
public class DefaultMessageFuture implements MessageFuture
{
	private Log log = LogFactory.getLog(DefaultMessageFuture.class);

	private final String message;
	private String replyMessage;

	private boolean done;
	private String errorCode;
	private String errorMessage;

	public String getMessage()
	{
		return message;
	}

	@Override
	public String getReplyMessage()
	{
		return replyMessage;
	}

	public DefaultMessageFuture(String message)
	{
		this.message = message;
	}

	@Override
	public boolean await(long timeoutMillis) throws InterruptedException
	{
		if (Thread.interrupted())
			throw new InterruptedException();

		synchronized (this)
		{
			if (done)
				return done;
			else if (timeoutMillis <= 0)
				return done;

			try
			{
				this.wait(timeoutMillis);
			}
			catch (InterruptedException e)
			{
				log.error(e.getMessage(), e);
				throw e;
			}
			return done;
		}
	}

	@Override
	public boolean setSuccess()
	{
		return setSuccess(null);
	}

	@Override
	public boolean setSuccess(String replyMessage)
	{
		synchronized (this)
		{
			// Allow only once.
			if (done)
				return false;

			this.replyMessage = replyMessage;
			done = true;
			notifyAll();
		}
		return true;
	}

	@Override
	public boolean setFailure(String responseCode)
	{
		synchronized (this)
		{
			// Allow only once.
			if (done)
			{
				return false;
			}

			this.errorCode = responseCode;
			//TODO luoyp			this.errorMessage =
			done = true;
			notifyAll();

		}

		return true;
	}

	@Override
	public boolean isDone()
	{
		return done;
	}

	@Override
	public boolean isSuccess()
	{
		return done && errorCode == null;
	}

	@Override
	public String getErrorCode()
	{
		return errorCode;
	}

	@Override
	public String getErrorMessage()
	{
		return errorMessage;
	}
}
